<?php
/**
 * Model for the users and userpermissions.
 */
class UsersModel
{
	/**
	 * Gets all users from the database and stores them in an array as User-objects.
	 * @return array An array that contains User-objects.
	 */
	public function GetAllUsers()
	{
        require_once 'User.php';
        
        require_once "../" . Settings::DBPath();
        
        $DB = new Database();
        
        $users = array();
	
		if ( $DB->Connect() )
		{
			$statement = $DB->Prepare( "SELECT UserID, Username, Password, Email FROM users" );
			$statement->execute();
			$statement->bind_result( $userID, $username, $password, $email );

			$i = 0;

			while ( $statement->fetch() )
			{
				$users[$i]['permissions'] = array();
				
				$users[$i]['id'] = $userID;
				$users[$i]['name'] = $username; 
				$users[$i]['password'] = $password;
				$users[$i]['email'] = $email;
				
				$i++;
			}
	
			$statement->Close();
			
			$userCount = count( $users );
			
			for ( $i = 0; $i < $userCount; $i++ )
			{
				$userID = $users[$i]['id'];
				$stmt = $DB->Prepare( "SELECT PermissionID FROM userpermissions WHERE UserID=? " );
				$stmt->bind_param( "i", $userID );
				$stmt->execute();
				$stmt->bind_result( $permissionID );
				
			   	while ( $stmt->fetch() )
				{
					$users[$i]['permissions'][] = $permissionID;
				}
				
				$stmt->Close();
			}
		
			$DB->Close();
		}
        
        return $users;
	}
	
	/**
	* Deletes the user from the database.
	* @param int $userID Contains the UserID to delete.
	* @return bool True/False if user was deleted from the database or not.
	*/
	public function DeleteUser( $userID )
	{
		require_once '../' . Settings::DBPath();
        
		$DB = new Database();
		$status = false;
        
		if ( $DB->Connect() )
		{
			$statement = $DB->Prepare( "DELETE FROM users WHERE UserID=?" );
			$statement->bind_param( "i", $userID );
			$statement->execute();
			
			if ( $DB->CountAffectedRows() > 0 )
			{
				$status = true;
			}
            
			$statement->Close();
            
            $DB->Close();
		}
        
        return $status;
	}
	
	/**
	* Gets the user from the database by the userId.
	* @param int $userID The userID to use to get the user.
	* @return User A User-object.
	*/
	public function GetUserByID( $userID )
	{
		require_once '../' . Settings::DBPath();
        require_once 'User.php';
        
		$DB = new Database();
        $user = null;
        
		if ( $DB->Connect() )
		{
			$statement = $DB->Prepare( "SELECT UserID, Username, Password, Email FROM users WHERE UserID=? " );
			$statement->bind_param( "i", $userID );
			$statement->execute();
			$statement->bind_result( $userID, $username, $password, $email );
			$statement->fetch();
            
            $user = new User( $userID, $username, $password, $email );
            
            $statement->Close();
            
			$DB->Close();
		}
        
        return $user;
	}
	
	/**
	 * Saves the changes to the database.
	 * @param int $userID The UserID to save to in the database.
	 * @param string $newPassword The new password (SHA1-encrypted below).
	 * @param string $email The new e-mail adress.
	 */
	public function SaveChanges( $userID, $username, $newPassword, $email )
	{
		require_once '../' . Settings::DBPath();
        
		$DB = new Database();
		$status = false;
        
		if ( $DB->Connect() )
		{
			$statement = $DB->Prepare( "UPDATE users SET Password=?, Username=?, Email=? WHERE UserID=?" );
			$statement->bind_param( "sssi", $newPassword, $username, $email, $userID );
			$statement->execute();
			
			if ( $DB->CountAffectedRows() > 0 )
			{
				$status = true;
			}
            
            $statement->Close();
            
            $DB->Close();
		}
        
        return $status;
	}
	
	public function CreateUser( $username, $password, $email )
	{
		require_once '../' . Settings::DBPath();
		$DB = new Database();
		
		$status = false;
		
		if ( $DB->Connect() )
		{
			// Check if the users exits.
			$stmt = $DB->Prepare( "SELECT COUNT( UserID ) FROM users WHERE Email = ?" );
			$stmt->bind_param( "s", $email );
			$stmt->execute();
			$stmt->bind_result( $row_userCount );
			$stmt->fetch();
			$userExists = $row_userCount > 0;
			$stmt->close(); 
			
			if ( ! $userExists )
			{
				$password = sha1( $password );
				
				$stmt = $DB->Prepare( "INSERT INTO users (Username, Password, Email) VALUES (?, ?, ?)" );
				$stmt->bind_param( "sss", $username, $password, $email );
				$stmt->execute();
				$stmt->close();
				
				$status = true;
			}
		    
			// SHA1-encrypt the password.
		    // Store user in the database.
			$DB->Close();
		}
		
		return $status;
	}
	
	
	/*==================== PERMISSION ====================*/
	
	/**
	 * Gets all users from the database and stores them in an array as User-objects.
	 * @return array An array that contains User-objects.
	 */
	public function GetAllPermissions()
	{
        require_once 'Permission.php';
        
        require_once "../" . Settings::DBPath();
        
        $DB = new Database();
        
        $users = array();
	
		if ( $DB->Connect() )
		{
			$stmt = $DB->Prepare( "SELECT PermissionID, Name FROM permissions" );
			$stmt->execute();
			$stmt->bind_result( $permissionID, $name );

			while ( $stmt->fetch() )
			{
				$permissions[] = new Permission( $permissionID, $name );
			}
	
			$stmt->Close();
	
            $DB->Close();
		}
        
        return $permissions;
	}
	
	public function GetPermissionsByUserID( $userID )
	{
        require_once "../" . Settings::DBPath();
        
        $DB = new Database();
        $userpermissions = array();
        
		if ( $DB->Connect() )
		{
			$stmt = $DB->Prepare( "SELECT PermissionID FROM userpermissions WHERE UserID=? " );
			$stmt->bind_param( "i", $userID );
			$stmt->execute();
			$stmt->bind_result( $permissionID );
            
           while ( $stmt->fetch() )
			{
				$userpermissions[] = $permissionID;
			}
            
            $stmt->Close();
            
			$DB->Close();
		}
        
        return $userpermissions;
	}
}
